<template>
  <el-dialog :visible.sync="visible" :title="title" width="50%">
    <el-form :model="formData" ref="form" label-width="120px" :rules="rules">
      <el-form-item v-for="(item, index) in formItems" :key="index" :label="item.label" :prop="item.name">
        <el-input v-if="item.type === 'input'" v-model="formData[item.name]" :placeholder="item.placeholder" />
        <el-select v-if="item.type === 'select'" v-model="formData[item.name]" :placeholder="item.placeholder">
          <el-option v-for="option in item.options" :key="option.value" :label="option.label" :value="option.value" />
        </el-select>
        <!-- 你可以扩展更多组件类型 -->
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="submitForm">提交</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  name: 'formDialogComponent',
  data() {
    return {
      visible: false,
      title: '',
      formItems: [], //表单数组
      formData: {},
      rules: {} // 存储表单验证规则
    };
  },
  watch: {
    formItems: {
      handler(newItems) {
        // 初始化 formData 和验证规则
        this.formData = this.initFormData(newItems);
        this.rules = this.initValidationRules(newItems);
      },
      immediate: true
    }
  },
  methods: {
    showDialog(val) {
      this.visible = true;
      console.log(val);
    },
    // 初始化表单数据
    initFormData(items) {
      return items.reduce((acc, item) => {
        acc[item.name] = item.value || '';
        return acc;
      }, {});
    },

    // 自动生成验证规则
    initValidationRules(items) {
      return items.reduce((acc, item) => {
        const rule = [];
        if (item.required) {
          rule.push({ required: true, message: `${item.label}不能为空`, trigger: 'blur' });
        }
        if (item.validator) {
          rule.push(item.validator);
        }
        if (rule.length) acc[item.name] = rule;
        return acc;
      }, {});
    },

    // 提交表单
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$emit('submit', this.formData);
          this.visible = false;
        } else {
          console.log('表单验证失败');
        }
      });
    }
  }
};
</script>
